<template>
  <div class="sensitive-word-container">
    <!-- 搜索和批量操作栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="请输入关键词" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option label="脏话" value="dirty" />
            <el-option label="政治" value="political" />
            <el-option label="色情" value="porn" />
            <el-option label="广告" value="ads" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 敏感词列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>敏感词列表</span>
          <div>
            <el-button type="primary" @click="showAddDialog" :icon="Plus">添加敏感词</el-button>
            <el-button type="success" @click="showBatchImportDialog">批量导入</el-button>
            <el-button type="danger" :disabled="selectedIds.length === 0" @click="batchDelete">
              批量删除
            </el-button>
          </div>
        </div>
      </template>

      <el-table 
        :data="wordList" 
        v-loading="loading" 
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="word" label="敏感词" min-width="150" show-overflow-tooltip />
        <el-table-column prop="category" label="分类" width="100">
          <template #default="{ row }">
            <el-tag :type="getCategoryColor(row.category)">{{ getCategoryName(row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="replacement" label="替换词" min-width="100" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.replacement || '***' }}
          </template>
        </el-table-column>
        <el-table-column prop="matchCount" label="匹配次数" width="100" />
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="editWord(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteWord(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 12px;">
        <span class="selected-info">已选择 {{ selectedIds.length }} 条</span>
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="敏感词" prop="word">
          <el-input v-model="formData.word" placeholder="请输入敏感词" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择分类">
            <el-option label="脏话" value="dirty" />
            <el-option label="政治" value="political" />
            <el-option label="色情" value="porn" />
            <el-option label="广告" value="ads" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="替换词">
          <el-input 
            v-model="formData.replacement" 
            placeholder="留空则默认使用 ***" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveWord">确定</el-button>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog 
      v-model="importDialogVisible" 
      title="批量导入敏感词" 
      width="600px"
    >
      <el-form :model="importForm" label-width="100px">
        <el-form-item label="分类">
          <el-select v-model="importForm.category" placeholder="请选择分类">
            <el-option label="脏话" value="dirty" />
            <el-option label="政治" value="political" />
            <el-option label="色情" value="porn" />
            <el-option label="广告" value="ads" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="敏感词列表">
          <el-input
            v-model="importForm.words"
            type="textarea"
            :rows="10"
            placeholder="每行一个敏感词"
          />
          <div class="import-tip">提示：每行输入一个敏感词，系统会自动去重</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="batchImport">确定导入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'

const searchForm = reactive({
  keyword: '',
  category: ''
})

const wordList = ref([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)
const selectedIds = ref([])

const dialogVisible = ref(false)
const dialogTitle = ref('添加敏感词')
const formRef = ref(null)
const formData = reactive({
  id: null,
  word: '',
  category: 'other',
  replacement: ''
})

const rules = {
  word: [{ required: true, message: '请输入敏感词', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }]
}

const importDialogVisible = ref(false)
const importForm = reactive({
  category: 'other',
  words: ''
})

// 获取敏感词列表
const getWordList = async () => {
  loading.value = true
  try {
    const response = await request.get('/admin/sensitive-word/list', {
      params: {
        keyword: searchForm.keyword,
        category: searchForm.category,
        page: page.value,
        pageSize: pageSize.value
      }
    })
    if (response.code === 0) {
      wordList.value = response.data.list
      total.value = response.data.total
    }
  } catch (error) {
    ElMessage.error('获取敏感词列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  getWordList()
}

// 重置
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.category = ''
  page.value = 1
  getWordList()
}

// 分页
const handleCurrentChange = (val) => {
  page.value = val
  getWordList()
}

// 选择改变
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加敏感词'
  formData.id = null
  formData.word = ''
  formData.category = 'other'
  formData.replacement = ''
  dialogVisible.value = true
}

// 编辑敏感词
const editWord = (row) => {
  dialogTitle.value = '编辑敏感词'
  formData.id = row.id
  formData.word = row.word
  formData.category = row.category
  formData.replacement = row.replacement || ''
  dialogVisible.value = true
}

// 保存敏感词
const saveWord = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const url = formData.id 
          ? `/admin/sensitive-word/update/${formData.id}`
          : '/admin/sensitive-word/create'
        const method = formData.id ? 'put' : 'post'
        
        const response = await request[method](url, formData)
        if (response.code === 0) {
          ElMessage.success('保存成功')
          dialogVisible.value = false
          getWordList()
        }
      } catch (error) {
        ElMessage.error('保存失败')
      }
    }
  })
}

// 删除敏感词
const deleteWord = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除此敏感词吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await request.delete(`/admin/sensitive-word/delete/${id}`)
    if (response.code === 0) {
      ElMessage.success('删除成功')
      getWordList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请先选择要删除的敏感词')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个敏感词吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await request.post('/admin/sensitive-word/batch-delete', {
      ids: selectedIds.value
    })
    if (response.code === 0) {
      ElMessage.success('批量删除成功')
      selectedIds.value = []
      getWordList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 显示批量导入对话框
const showBatchImportDialog = () => {
  importForm.category = 'other'
  importForm.words = ''
  importDialogVisible.value = true
}

// 批量导入
const batchImport = async () => {
  if (!importForm.words.trim()) {
    ElMessage.warning('请输入要导入的敏感词')
    return
  }

  const words = importForm.words.split('\n')
    .map(w => w.trim())
    .filter(w => w.length > 0)

  if (words.length === 0) {
    ElMessage.warning('没有有效的敏感词')
    return
  }

  try {
    const response = await request.post('/admin/sensitive-word/batch-import', {
      category: importForm.category,
      words: words
    })
    if (response.code === 0) {
      ElMessage.success(`成功导入 ${response.data.count} 个敏感词`)
      importDialogVisible.value = false
      getWordList()
    }
  } catch (error) {
    ElMessage.error('导入失败')
  }
}

// 获取分类名称
const getCategoryName = (category) => {
  const map = {
    dirty: '脏话',
    political: '政治',
    porn: '色情',
    ads: '广告',
    other: '其他'
  }
  return map[category] || category
}

// 获取分类颜色
const getCategoryColor = (category) => {
  const map = {
    dirty: 'warning',
    political: 'danger',
    porn: 'danger',
    ads: 'info',
    other: ''
  }
  return map[category] || ''
}

onMounted(() => {
  getWordList()
})
</script>

<style scoped>
.sensitive-word-container {
  padding: 20px;
}

.search-card,
.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-info {
  color: #666;
  font-size: 14px;
}

.import-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}
</style>
